package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api")
@Tag(name = "用户管理", description = "系统用户管理和用户中心功能")
public class UserManagementController {
    
    @Autowired
    private UserService userService;

    // ==================== 管理员用户管理 ====================

    @GetMapping("/auth/users/{id}")
    @Operation(summary = "获取用户详情")
    public ResponseEntity<User> getUserDetail(@PathVariable Long id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/auth/users/{id}")
    @Operation(summary = "更新用户信息")
    public ResponseEntity<User> updateUser(
            @PathVariable Long id,
            @Valid @RequestBody User user) {
        return userService.getUserById(id)
                .map(existingUser -> {
                    user.setId(id);
                    User updatedUser = userService.updateUser(user);
                    return ResponseEntity.ok(updatedUser);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/auth/users/{id}")
    @Operation(summary = "删除用户")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        if (userService.getUserById(id).isPresent()) {
            userService.deleteUser(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping("/admin/users")
    @Operation(summary = "创建用户")
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        User createdUser = userService.createUser(user);
        return ResponseEntity.ok(createdUser);
    }

    @PutMapping("/admin/users/{id}/status")
    @Operation(summary = "更新用户状态")
    public ResponseEntity<User> updateUserStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusUpdate) {
        
        return userService.getUserById(id)
                .map(user -> {
                    String status = statusUpdate.get("status");
                    user.setStatus(status);
                    User updatedUser = userService.updateUser(user);
                    return ResponseEntity.ok(updatedUser);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    // ==================== 用户中心功能 ====================


    @PostMapping("/auth/refresh")
    @Operation(summary = "刷新Token")
    public ResponseEntity<Map<String, Object>> refreshToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            // 这里应该验证token并生成新的token
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "Token刷新成功");
            response.put("token", "new_jwt_token_here");
            return ResponseEntity.ok(response);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "无效的token");
        return ResponseEntity.badRequest().body(response);
    }



    @PostMapping("/auth/reset-password")
    @Operation(summary = "重置密码")
    public ResponseEntity<Map<String, Object>> resetPassword(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");
        String newPassword = request.get("newPassword");

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "密码重置成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/auth/send-code")
    @Operation(summary = "发送验证码")
    public ResponseEntity<Map<String, Object>> sendVerificationCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String type = request.get("type"); // "reset_password", "register", etc.

        // 这里应该实现发送验证码的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "验证码已发送");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/auth/verify-code")
    @Operation(summary = "验证验证码")
    public ResponseEntity<Map<String, Object>> verifyCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");

        // 这里应该实现验证码验证逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "验证码正确");
        return ResponseEntity.ok(response);
    }



    // ==================== 商家端用户管理 ====================
    @PostMapping("/merchant/login")
    @Operation(summary = "商家登录")
    public ResponseEntity<Map<String, Object>> merchantLogin(
            @RequestBody Map<String, String> loginData) {
        
        // 这里应该实现商家登录逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("token", "mock-token");
        return ResponseEntity.ok(response);
    }


}
